#include<fuquOS/stdio.h>

// 初始化内存池
void init_memory_pool() {
    free_list = (Block *)memory_pool;
    free_list->size = MEM_POOL_SIZE - BLOCK_SIZE;  // 初始块大小为整个内存池的大小
    free_list->next = NULL;
}

// malloc函数实现
void *malloc(u32 size) {
    if (size == 0) {
        return NULL;
    }

    // 内存块需要对齐到8字节
    size = (size + 7) & ~7;

    Block *prev = NULL;
    Block *current = free_list;

    while (current != NULL) {
        if (current->size >= size) {
            // 找到合适的块
            if (current->size > size + BLOCK_SIZE) {
                // 如果剩余空间足够大，可以将块分割
                Block *new_block = (Block *)((char *)current + BLOCK_SIZE + size);
                new_block->size = current->size - size - BLOCK_SIZE;
                new_block->next = current->next;

                current->size = size;
                current->next = new_block;
            }

            // 从空闲链表中移除当前块
            if (prev != NULL) {
                prev->next = current->next;
            } else {
                free_list = current->next;
            }

            return (char *)current + BLOCK_SIZE;  // 返回内存块的实际地址
        }

        prev = current;
        current = current->next;
    }

    // 如果没有找到合适的空闲块，则返回NULL
    return NULL;
}

// free函数实现
void free(void *ptr) {
    if (ptr == NULL) {
        return;
    }

    // 获取Block结构的地址
    Block *block = (Block *)((char *)ptr - BLOCK_SIZE);

    // 将释放的块添加到空闲链表
    block->next = free_list;
    free_list = block;
}

